package com.kehutong.charge.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.kehutong.charge.entity.*;
import org.coraframework.bean.Beans;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.connection.ThreadLocalCache;
import org.coraframework.util.Objects;
import com.kehutong.charge.service.CategoryBillService;
import com.kehutong.charge.service.CommonService;
import com.kehutong.charge.util.CommonClient;
import com.kehutong.charge.util.CommonUtil;
import com.kehutong.charge.util.ConvertUtil;
import com.kehutong.charge.util.enums.ChargeBillStatusEnum;
import com.kehutong.charge.util.enums.ChargeCalcEnum;
import com.kehutong.charge.util.enums.ChargeLogEnum;
import com.kehutong.common.DoveClient;
import com.kehutong.common.Java8TimeUtils;
import com.kehutong.common.dto.UniformSendReqDto;
import com.kehutong.common.enums.MessageBusinessEnum;
import com.kehutong.common.enums.TemplateType;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.BigDecimalUtils;
import com.kehutong.common.util.TemplateReplaceUtil;

/**
 * 类目账单服务类
 *
 * @author wupengfei
 */
public class CategoryBillServiceImpl implements CategoryBillService {

    private static final Logger logger = LoggerFactory.getLogger(CategoryBillServiceImpl.class);

    @Inject
    private CommonClient commonClient;

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private CommonService commonService;

    @Inject
    private DoveClient doveClient;

    @Override
    public Object save(ChargeBillItems chargeBillItems) throws Exception {
        logger.info("保存类目账单" + chargeBillItems.toString());
        // 获取房屋列表
        List<String> houseNoList = getHouseNo(chargeBillItems);

        return generateItemBill(chargeBillItems, houseNoList, false);
    }

    private Object generateItemBill(ChargeBillItems chargeBillItems, List<String> houseList, boolean isAll) throws Exception {
        //生成小区账单
        ChargeBillCommunity community = jdbcSession.findOne(ChargeBillCommunity.class).eq("communityNo", chargeBillItems.getCommunityNo())
                .eq("billYearMonth", chargeBillItems.getBillYearMonth()).eq("billStatus", ChargeBillStatusEnum.BILL_WAIT_PAID.getId())
                .exe();
        boolean isAdd = false;
        String communityBillNo = null;
        if (community == null) {
            isAdd = true;
            community = Pool.newInstance(ChargeBillCommunity.class);
            communityBillNo = CommonUtil.generateRandom("XQ");
        }
        community.setCommunityBillNo(isAdd ? communityBillNo : community.getCommunityNo());
        chargeBillItems.setCommunityBillNo(community.getCommunityBillNo());

        // 获取出账日期
        ChargeBillConfig chargeBillConfig = jdbcSession.findOne(ChargeBillConfig.class).eq("communityNo", chargeBillItems.getCommunityNo())
                .eq("billYearMonth", chargeBillItems.getBillYearMonth()).exe();
        if (chargeBillConfig == null) {
            chargeBillConfig = Pool.newInstance(ChargeBillConfig.class);
            chargeBillConfig.setCommunityName(chargeBillItems.getCommunityName());
            chargeBillConfig.setCommunityNo(chargeBillItems.getCommunityNo());
            chargeBillConfig.setBillYearMonth(chargeBillItems.getBillYearMonth());
            chargeBillConfig.setBillDate(chargeBillItems.getBillDate());
            chargeBillConfig.setPayDate(chargeBillItems.getChargeDate());
            chargeBillConfig.setDefaultDate(chargeBillItems.getPenaltyDate());
            jdbcSession.insert(chargeBillConfig);
        }

        int generateNumber = 0;
        BigDecimal communityAmount = new BigDecimal(0);
        for (int b = 0; b < houseList.size(); b++) {
            String houseNo = houseList.get(b);

            //1、根据房屋id查询费用配置绑定项,可能配置多次
            ChargeHouseConfig houseConfig = jdbcSession.findOne(ChargeHouseConfig.class)
                    .eq("deleted", false)
                    .eq("houseNo", houseNo)
                    .exe();
            if (null == houseConfig) {
                logger.warn("房屋：{},没有设置收费项目！", houseNo);
                continue;
            }
            community.setCommunityName(houseConfig.getCommunityName());

            //查询配置类型
            String meterTypeNo = chargeBillItems.getMeterTypeNo();
            ChargeTypeConfig typeConfigs = jdbcSession.findOne(ChargeTypeConfig.class)
                    .eq("deleted", false)
                    .eq("meterTypeNo", meterTypeNo)
                    .exe();
            //查询费用配置项
            List<ChargeHouseSet> houseSetList = jdbcSession.findArray(ChargeHouseSet.class)
                    .eq("deleted", false)
                    .eq("chargeHouseNo", houseConfig.getId())
                    .eq("feeTypeNo", typeConfigs.getId())
                    .exe();
            if (null == houseSetList || 0 == houseSetList.size()) {
                logger.warn("房屋：{},没有设置收费项目！", houseNo);
                continue;
            }

            // 判断此房屋是否有已完成已缴费的账单
            List<ChargeBillHouse> paidHouseList = jdbcSession.findArray(ChargeBillHouse.class).eq("deleted", false).eq("houseNo", houseNo)
                    .eq("billYearMonth", chargeBillItems.getBillYearMonth())
                    .eq("billStatus", ChargeBillStatusEnum.BILL_PAID_FINISH)
                    .eq("chargeStatus", ChargeBillStatusEnum.BILL_PAID).exe();
            if (Objects.nonEmpty(paidHouseList)) {
                logger.warn("此房屋已有已缴费的账单");
                continue;
            }

            // 自动关闭此类型账单
            BigDecimal amountHouse = new BigDecimal(0);
            List<ChargeBillItems> billItems = jdbcSession.findArray(ChargeBillItems.class)
                    .eq("deleted", false)
                    .eq("houseNo", houseNo)
                    .eq("billYearMonth", chargeBillItems.getBillYearMonth())
                    .eq("meterTypeNo", meterTypeNo)
                    .eq("billStatus", ChargeBillStatusEnum.BILL_WAIT_PAID)
                    .exe();
            for (int i = 0; i < billItems.size(); i++) {
                ChargeBillItems each = billItems.get(i);
                each.setBillStatus(ChargeBillStatusEnum.BILL_PAID_CLOSE);
                each.setRemark("自动关闭");
                jdbcSession.updateById(each);
            }

            // 查询房屋账单（关闭待缴费的）
            List<ChargeBillHouse> houseBillList = jdbcSession.findArray(ChargeBillHouse.class)
                    .eq("deleted", false)
                    .eq("houseNo", houseNo)
                    .eq("billStatus", ChargeBillStatusEnum.BILL_WAIT_PAID.getId())
                    .eq("billYearMonth", chargeBillItems.getBillYearMonth()).exe();
            List<ChargeBillItems> unpaidBillItemList = new ArrayList<>();
            if (Objects.nonEmpty(houseBillList)) {
                // 根据状态值获取房屋账单
                List<ChargeBillHouse> unpaidList = new ArrayList<>();
                List<ChargeBillHouse> partPaidList = new ArrayList<>();
                for (ChargeBillHouse each : houseBillList) {
                    if (each.getChargeStatus() == ChargeBillStatusEnum.BILL_UN_PAID) {
                        each.setBillStatus(ChargeBillStatusEnum.BILL_PAID_CLOSE);
                        each.setAutoRemark("自动关闭");
                        unpaidList.add(each);
                    } else if (each.getChargeStatus() == ChargeBillStatusEnum.BILL_PAID_PART) {
                        each.setBillStatus(ChargeBillStatusEnum.BILL_PAID_CLOSE);
                        each.setAutoRemark("自动关闭");
                        partPaidList.add(each);
                    }

                    each.setBillStatus(ChargeBillStatusEnum.BILL_PAID_CLOSE);
                    each.setChargeStatus(ChargeBillStatusEnum.BILL_UN_PAID);
                    jdbcSession.updateById(each);
                }

                // 关闭待缴费的
                if (unpaidList.size() > 0) {
                    jdbcSession.updateById(unpaidList);

                    for (ChargeBillHouse each : unpaidList) {
                        List<ChargeBillItems> billItemIdList = jdbcSession.findArray(ChargeBillItems.class).in("houseBillNo", each.getHouseBillNo())
                                .eq("chargeStatus", ChargeBillStatusEnum.BILL_UN_PAID.getId())
                                .eq("billStatus", ChargeBillStatusEnum.BILL_WAIT_PAID.getId())
                                .exe();
                        if (billItemIdList.size() > 0) {
                            unpaidBillItemList.addAll(billItemIdList);
                        }

                        commonService.insetLogger(each.getHouseBillNo(),
                                ChargeLogEnum.LOG_CHARGE_BILL_COM.getDesc(),
                                "常规账单作废",
                                ChargeBillStatusEnum.BILL_PAID_CLOSE.getDesc(),
                                ChargeBillStatusEnum.BILL_UN_PAID.getDesc(), "操作成功", chargeBillItems.getCreateName());
                    }
                }

                // 部份付费的
                if (partPaidList.size() > 0) {
                    // 作废原账单
                    jdbcSession.updateById(partPaidList);
                    for (ChargeBillHouse each : partPaidList) {
                        commonService.insetLogger(each.getHouseBillNo(),
                                ChargeLogEnum.LOG_CHARGE_BILL_COM.getDesc(),
                                "常规账单作废",
                                ChargeBillStatusEnum.BILL_PAID_CLOSE.getDesc(),
                                ChargeBillStatusEnum.BILL_UN_PAID.getDesc(), "操作成功", chargeBillItems.getCreateName());
                    }

                    // 查询此房屋账单
                    for (ChargeBillHouse each : partPaidList) {
                        // 已付费的类目账单生成已缴费的新账单
                        List<ChargeBillItems> billItemIdList = jdbcSession.findArray(ChargeBillItems.class).in("houseBillNo", each.getHouseBillNo())
                                .eq("chargeStatus", ChargeBillStatusEnum.BILL_PAID.getId()).exe();
                        generatePaidHouseBill(each, billItemIdList);

                        // 已付费的类目账单中未付费的
                        billItemIdList = jdbcSession.findArray(ChargeBillItems.class).in("houseBillNo", each.getHouseBillNo())
                                .eq("chargeStatus", ChargeBillStatusEnum.BILL_UN_PAID.getId()).exe();
                        if (billItemIdList.size() > 0) {
                            unpaidBillItemList.addAll(billItemIdList);
                        }
                    }
                }
            }

            BigDecimal zero = new BigDecimal(0);
            ChargeBillHouse chargeBillHouse = generateHouseBill(chargeBillItems, houseConfig, houseNo, zero, zero);

            // 生成未缴费的新账单（现类目账单再加上原未缴费的）
            for (int i = 0; i < houseSetList.size(); i++) {
                //3、根据费用配置项id查询具体配置信息，并计算费用
                ChargeHouseSet chs = houseSetList.get(i);

                //4、查询费用配置参数
                ChargeProjectConfig pconfig = jdbcSession.findById(ChargeProjectConfig.class, chs.getProjectFeeNo());

                //5、查询仪表类型
                ChargeTypeConfig typeConfig = jdbcSession.findById(ChargeTypeConfig.class, pconfig.getFeeTypeNo());

                //6、根据房屋和类型、月份、周期、查询抄表使用量(有多次抄表的情况)
                List<MeterReading> meterReading = jdbcSession.findArray(MeterReading.class)
                        .eq("deleted", false)
                        .eq("houseNo", chs.getHouseNo())
                        .eq("meterTypeNo", meterTypeNo)
                        .like("endTime", chargeBillItems.getBillYearMonth())
                        .exe();

                if (null == meterReading || meterReading.size() == 0) {
                    logger.warn("房间：{},在{}没有抄表数据！", chs.getHouseNo(), chargeBillItems.getBillYearMonth());
                    continue;
                }

                generateNumber++;
                for (int j = 0; j < meterReading.size(); j++) {
                    MeterReading reading = meterReading.get(j);
                    ChargeBillItems items = Pool.newInstance(ChargeBillItems.class);
                    String billNO = CommonUtil.generateRandom("LM");
                    items.setItemBillNo(billNO);
                    items.setBillStatus(ChargeBillStatusEnum.BILL_WAIT_PAID);
                    items.setChargeStatus(ChargeBillStatusEnum.BILL_UN_PAID);

                    //7、计算单个类型的总费用
                    BigDecimal timeUseNumber = reading.getTimeUseNumber();
                    if (pconfig.getCalcEnum() == ChargeCalcEnum.MODE_AREA) {
                        timeUseNumber = new BigDecimal(houseConfig.getChargeArea());
                    }
                    BigDecimal amount = commonService.calcFeeCommon(pconfig, timeUseNumber, billNO);
                    amount = amount.setScale(2, BigDecimal.ROUND_UP); //保存两位小数,只入不舍
                    amountHouse = amountHouse.add(amount);

                    items.setBillAmount(amount);
                    items.setBuildNo(chargeBillHouse.getBuildNo());
                    items.setMergeName(chargeBillHouse.getMergeName());
                    items.setBuildName(chargeBillHouse.getBuildName());
                    items.setFeeTypeName(typeConfig.getFeeTypeName());
                    items.setFeeTypeNo(typeConfig.getId());
                    items.setChargeName(chs.getChargeName());
                    items.setUserNo(chs.getChargeId());
                    items.setResidentsType(chs.getReType());
                    items.setCreateName(chargeBillItems.getCreateName());
                    items.setBillCycleStart(chargeBillItems.getBillCycleStart());
                    items.setBillCycleEnd(chargeBillItems.getBillCycleEnd());
                    items.setBillDate(chargeBillItems.getBillDate());
                    items.setChargeDate(chargeBillItems.getChargeDate());
                    items.setDepartmentNo(chargeBillItems.getDepartmentNo());
                    items.setDepartmentName(chargeBillItems.getDepartmentName());
                    items.setDepartmentNos(chargeBillItems.getDepartmentNos());
                    items.setCommunityNo(reading.getCommunityNo());
                    items.setCommunityName(reading.getCommunityName());
                    items.setCommunityBillNo(chargeBillItems.getCommunityBillNo());
                    items.setHouseNo(chs.getHouseNo());
                    items.setHouseBillNo(chargeBillHouse.getHouseBillNo());
                    items.setMeterTypeNo(reading.getMeterTypeNo());
                    items.setMeterTypeName(reading.getMeterTypeName());
                    items.setMeterClassifyName(reading.getMeterClassifyName());
                    items.setMeterClassifyNo(reading.getMeterClassifyNo());
                    items.setBillYearMonth(chargeBillHouse.getBillYearMonth());
                    items.setUsageNumber(reading.getTimeUseNumber());
                    items.setBillAddress(reading.getMeterAddress());
                    items.setPenaltyDays(Java8TimeUtils.subDate(chargeBillItems.getPenaltyDate()));
                    items.setPenaltyAmount(new BigDecimal(0));
                    items.setPenaltyDate(chargeBillItems.getPenaltyDate());
                    items.setCalcUnit(reading.getCalcUnit());
                    items.setPayableAmount(amount);
                    items.setPrice(pconfig.getPrice());
                    items.setLastTimeNumber(reading.getLastTimeNumber());
                    items.setTimeNumber(reading.getTimeNumber());
                    items.setStartTime(reading.getStartTime());
                    items.setEndTime(reading.getEndTime());

                    //8、记录费用项
                    jdbcSession.insert(items);

                    commonService.insetLogger(items.getItemBillNo(),
                            ChargeLogEnum.LOG_CHARGE_BILL_CATE.getDesc(),
                            "创建类目账单",
                            ChargeBillStatusEnum.BILL_WAIT_PAID.getDesc(),
                            ChargeBillStatusEnum.BILL_UN_PAID.getDesc(), "操作成功", chargeBillItems.getCreateName());

                    //9.更新数据
                   List<ChargeBillLadder> billLadders = jdbcSession.findArray(ChargeBillLadder.class)
                           .eq("itemBillNo",items.getItemBillNo()).exe();
                    for (int k = 0; k < billLadders.size(); k++) {
                        ChargeBillLadder ladder = billLadders.get(k);
                        ladder.setMeterTypeNo(items.getMeterTypeNo());
                        ladder.setMeterTypeName(items.getMeterTypeName());
                        ladder.setHouseNo(items.getHouseNo());
                        ladder.setBillYearMonth(items.getBillYearMonth());
                    }

                    try{
                        //根据用户查询手机号码
                        JSONObject object = commonClient.findResidentInfo(items.getUserNo());

                        //切换公司
                        String companyNo = ThreadLocalCache.current().getCorpId();
                        ChargeOrderManage manage = Pool.newInstance(ChargeOrderManage.class);
                        List<String> phoneList = new ArrayList<>();
                        phoneList.add(object.getString("mobile")); //手机号
                        msgUniformSend(items,items.getUserNo(), TemplateType.PAY_C_MONTH_BILL_DATE, phoneList,true, companyNo);
                    }catch (Exception e){}
                }
            }

            // 保存房屋账单
            if (unpaidBillItemList.size() > 0) {
                for (ChargeBillItems each : unpaidBillItemList) {
                    each.setBuildNo(chargeBillHouse.getBuildNo());
                    each.setMergeName(chargeBillHouse.getMergeName());
                    each.setBuildName(chargeBillHouse.getBuildName());
                    each.setHouseBillNo(chargeBillHouse.getHouseBillNo());
                    each.setBillYearMonth(chargeBillHouse.getBillYearMonth());
                    amountHouse = amountHouse.add(each.getBillAmount());
                }
                jdbcSession.updateById(unpaidBillItemList);
            }
            communityAmount = BigDecimalUtils.add(communityAmount, amountHouse, 2);
            chargeBillHouse.setBillAmount(amountHouse);
            chargeBillHouse.setBillAmountUnPaid(amountHouse);
            jdbcSession.insert(chargeBillHouse);
        }

        community.setBillAmountTotal(communityAmount);
        community.setBillTotal(generateNumber);
        community.setCommunityNo(chargeBillItems.getCommunityNo());
        community.setBillStatus(ChargeBillStatusEnum.BILL_WAIT_PAID);
        community.setCreateName(chargeBillItems.getCreateName());
        community.setBillCycleStart(chargeBillItems.getBillCycleStart());
        community.setBillCycleEnd(chargeBillItems.getBillCycleEnd());
        community.setBillDate(chargeBillItems.getBillDate());
        community.setChargeDate(chargeBillItems.getChargeDate());
        community.setBillYearMonth(chargeBillItems.getBillYearMonth());
        community.setPenaltyDate(chargeBillItems.getPenaltyDate());
        community.setDepartmentNo(chargeBillItems.getDepartmentNo());
        community.setDepartmentName(chargeBillItems.getDepartmentName());
        community.setDepartmentNos(chargeBillItems.getDepartmentNos());
        if (isAdd) {
            jdbcSession.insert(community);
        } else {
            jdbcSession.updateById(community);
        }

        return Result.success();
    }

    private List<String> getHouseNo(ChargeBillItems chargeBillItems) throws Exception {
        //定义房屋集合
        List<String> result = new ArrayList<>();

        //楼栋集合
        List<String> buildNoList = chargeBillItems.getBuildNoList();
        if (!Objects.isEmpty(buildNoList)) {
            for (int i = 0; i < buildNoList.size(); i++) {
                Map<String, JSONObject> objectMap = commonClient.getBuildMap(buildNoList.get(i));
                result.addAll(objectMap.keySet());
            }
        }

        //房屋集合
        List<String> houseNoList = chargeBillItems.getHouseNoList();
        if (!Objects.isEmpty(houseNoList)) {
            result.addAll(houseNoList);
        }

        //如果楼栋和房屋都没有选，则生成整个小区账单
        result.removeAll(Collections.singleton(null));
        if (Objects.isEmpty(result)) {
            Map<String, JSONObject> objectMap = commonClient.getHouseMap(chargeBillItems.getCommunityNo());
            result.addAll(objectMap.keySet());
        }
        return result;
    }

    /**
     * 发送消息
     * @param manage 模板替换内容对象
     * @param uuid 用户ID
     * @param templateType  模板CODE
     * @param phoneList 手机号
     * @param userCreate 是否小程序用户，false 员工，true 小程序用户
     * @throws Exception
     */
    private void msgUniformSend(ChargeBillItems manage, String uuid, TemplateType templateType, List<String> phoneList, boolean userCreate, String companyNo) throws Exception {
        // 获取消息推送配置文件
        JSONObject configJson = doveClient.post("/crm/message/global/config/service/get", (http) -> {
            http.addParam("templateType", templateType.getId());
        });

        if (configJson.getIntValue("code") == 200) {
            UniformSendReqDto dto = getUniformSendReqDto(manage, uuid, templateType, phoneList, configJson.getJSONObject("data"), userCreate, companyNo);
            // 消息推送
            doveClient.post("/crm/message/service/uniformSend", (http) -> {
                http.addParam("temp", JSONObject.toJSONString(dto));
            });
        }
    }

    private UniformSendReqDto getUniformSendReqDto(ChargeBillItems manage, String uuid, TemplateType templateType,
                                                   List<String> phoneList, JSONObject dataJson, boolean userCreate,
                                                   String companyNo) throws Exception {
        UniformSendReqDto dto = new UniformSendReqDto();
        dto.setMsgId(manage.getId());
        dto.setBusinessTypeId(MessageBusinessEnum.MSG_BILL_PAY.getId());
        dto.setTemplateTypeId(templateType.getId());
        dto.setCompanyNo(companyNo);
        dto.setUserCreate(userCreate);
        dto.setUuid(uuid);
        dto.setTitle("缴费提醒");

        JSONObject inner = dataJson.getJSONObject("messageTemplateInner");
        if (dataJson.getBooleanValue("innerSend") && org.coraframework.util.Objects.nonNull(inner)) {
            dto.setTitle(inner.getString("title"));
            dto.setInnerData(TemplateReplaceUtil.replace(inner.getString("content"), inner.getString("tagArray"), manage));
            dto.setPageParam(String.format("companyNo=%s&houseNo=%s", companyNo, manage.getHouseNo()));
        }

        JSONObject sms = dataJson.getJSONObject("messageTemplateSms");
        if (dataJson.getBooleanValue("smsSend") && org.coraframework.util.Objects.nonNull(sms)) {
            if (org.coraframework.util.Objects.nonEmpty(phoneList)){
                dto.setPhoneList(phoneList);
                dto.setSmsDataParams(TemplateReplaceUtil.listTencentSmsParam(sms.getString("content"), sms.getString("tagArray"), manage));
            } else {
                JSONObject jsonObject = doveClient.post("/kht-bin/auth/user/listPhone", http -> {
                    JSONObject temp = new JSONObject();
                    temp.put("id", Arrays.asList(uuid));
                    http.setBody(temp.toJSONString());
                });
                List<String> listPhone = JSONArray.parseArray(jsonObject.getString("data"), String.class);
                if (org.coraframework.util.Objects.nonEmpty(listPhone)){
                    dto.setPhoneList(listPhone);
                    dto.setSmsDataParams(TemplateReplaceUtil.listTencentSmsParam(sms.getString("content"), sms.getString("tagArray"), manage));
                }
            }

        }

        String wxchatTemplate = dataJson.getString("wxchatTemplate");
        if (dataJson.getBooleanValue("wxchatSend") && org.coraframework.util.Objects.nonNull(wxchatTemplate)) {
            dto.setWxChatData(getWxchatTemplate(templateType, manage));
            dto.setPageParam(String.format("companyNo=%s&houseNo=%s", companyNo, manage.getHouseNo()));
        }

        return dto;
    }

    private String getWxchatTemplate(TemplateType templateType, ChargeBillItems manage){
        JSONObject data = new JSONObject();

        if(TemplateType.PAY_C_MONTH_BILL_DATE == templateType){

            data.put("first", buildMpMessageData("您的月度账单已生成"));
            // 房号
            data.put("keyword1", buildMpMessageData(manage.getBillAddress()));
            // 账单年月
            data.put("keyword2", buildMpMessageData(manage.getBillYearMonth()));
            // 账单金额
            data.put("keyword3", buildMpMessageData(BigDecimalUtils.format(manage.getBillAmount()).toPlainString()));

            data.put("remark", buildMpMessageData("感谢您的关注和支持！如有疑问，请咨询物业管理处"));
            return data.toJSONString();
        } else {
            return null;
        }
    }

    private JSONObject buildMpMessageData(String value) {
        JSONObject json = new JSONObject();
        json.put("value", value);
        return json;
    }

    private ChargeBillHouse generateHouseBill(ChargeBillItems chargeBillItems, ChargeHouseConfig houseConfig,
                                              String houseNo, BigDecimal billAmount, BigDecimal billAmountUnPaid) throws Exception {
        //生成账单
        ChargeBillHouse chargeBillHouse = Pool.newInstance(ChargeBillHouse.class);
        chargeBillHouse.setHouseBillNo(CommonUtil.generateRandom("FW"));
        chargeBillHouse.setChargeName(houseConfig.getChargeName());
        chargeBillHouse.setResidentsType(houseConfig.getReType());
        chargeBillHouse.setBillYearMonth(chargeBillItems.getBillYearMonth());
        chargeBillHouse.setUserNo(houseConfig.getOwnerNo());
        chargeBillHouse.setHouseNo(houseNo);

        //查询该房屋的基本信息
        JSONObject jsonOb = commonClient.getHouseById(chargeBillItems.getRemark(), chargeBillHouse.getHouseNo());
        String communityName = jsonOb.getString("communityName");
        String buildName = jsonOb.getString("buildName");
        String mergeName = jsonOb.getString("mergeName");
        String unitName = jsonOb.getString("unitName");
        String address = ConvertUtil.jointAddress(communityName,buildName,unitName,mergeName);
        chargeBillHouse.setBillAddress(address);
        chargeBillHouse.setBuildNo(jsonOb.getString("buildNo"));
        chargeBillHouse.setBuildName(buildName);
        chargeBillHouse.setCommunityName(communityName);
        chargeBillHouse.setMergeName(mergeName);
        chargeBillHouse.setBillAmount(billAmount);
        chargeBillHouse.setBillAmountUnPaid(billAmountUnPaid);

        chargeBillHouse.setCommunityNo(chargeBillItems.getCommunityNo());
        chargeBillHouse.setCommunityBillNo(chargeBillItems.getCommunityBillNo());
        chargeBillHouse.setBillStatus(ChargeBillStatusEnum.BILL_WAIT_PAID);
        chargeBillHouse.setChargeStatus(ChargeBillStatusEnum.BILL_UN_PAID);
        chargeBillHouse.setBillCycleStart(chargeBillItems.getBillCycleStart());
        chargeBillHouse.setBillCycleEnd(chargeBillItems.getBillCycleEnd());
        chargeBillHouse.setBillDate(chargeBillItems.getBillDate());
        chargeBillHouse.setChargeDate(chargeBillItems.getChargeDate());
        chargeBillHouse.setPenaltyDate(chargeBillItems.getPenaltyDate());
        //计算违约天数,生成账单没有违约
        chargeBillHouse.setPenaltyDays(Java8TimeUtils.subDate(chargeBillItems.getPenaltyDate()));
        chargeBillHouse.setPenaltyAmount(new BigDecimal(0));
        chargeBillHouse.setDepartmentNo(chargeBillItems.getDepartmentNo());
        chargeBillHouse.setDepartmentName(chargeBillItems.getDepartmentName());
        chargeBillHouse.setDepartmentNos(chargeBillItems.getDepartmentNos());
        chargeBillHouse.setCreateName(chargeBillItems.getCreateName());

        commonService.insetLogger(chargeBillHouse.getHouseBillNo(),
                ChargeLogEnum.LOG_CHARGE_BILL_COM.getDesc(),
                "创建常规账单",
                ChargeBillStatusEnum.BILL_WAIT_PAID.getDesc(),
                ChargeBillStatusEnum.BILL_UN_PAID.getDesc(), "操作成功", chargeBillItems.getCreateName());
        return chargeBillHouse;
    }

    private void generatePaidHouseBill(ChargeBillHouse chargeBillHouse, List<ChargeBillItems> billItemIdList) {
        BigDecimal amount = new BigDecimal(0);
        for (ChargeBillItems each : billItemIdList) {
            amount = BigDecimalUtils.add(amount, each.getPaymentAmount(), 2);
        }
        ChargeBillHouse paidHouseBill = Pool.newInstance(ChargeBillHouse.class);
        Beans.from(chargeBillHouse).to(paidHouseBill).exclude("id").copy();
        paidHouseBill.setBillStatus(ChargeBillStatusEnum.BILL_PAID_FINISH);
        paidHouseBill.setChargeStatus(ChargeBillStatusEnum.BILL_PAID);
        paidHouseBill.setCommunityBillNo(CommonUtil.generateRandom("XQ"));
        paidHouseBill.setHouseBillNo(CommonUtil.generateRandom("FW"));
        paidHouseBill.setBillAmount(amount);
        paidHouseBill.setBillAmountPaid(amount);
        paidHouseBill.setBillAmountUnPaid(new BigDecimal(0));
        jdbcSession.insert(paidHouseBill);

        for (ChargeBillItems each : billItemIdList) {
            each.setHouseBillNo(paidHouseBill.getHouseBillNo());
            jdbcSession.updateById(each);
        }
    }
}
